/* eslint-disable camelcase */
/* eslint-disable no-useless-escape */
import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import { getAppPlatformsDatas } from "@redux/Action/nativeDatas/nativeDatas";
import MainLayout from "@component/mainLayout/mainLayout";
import { Tabs, NoticeBar, Modal, Button, Toast, List } from "antd-mobile";
import { InterfaceG, channelCode, agreements_url } from "@config/Config";
import yhTools from "@tools/yh";
import FooterIco from "@images/imageXHB/new-home/hedaer-footer-ic.png";
import HedaerIco from "@images/imageXHB/new-home/header-titile-ico.png";
import ListOne from "@images/imageXHB/new-home/list-three-one.png";
import ListTow from "@images/imageXHB/new-home/list-three-tow.png";
import ListThree from "@images/imageXHB/new-home/list-three-three.png";
import Course from "@images/imageXHB/new-home/course.png";
import RiskStatement from "@images/imageXHB/new-home/risk-statement.png";
import ArrowLeft from "@images/imageXHB/new-home/arrow-left.png";
import ArrowRight from "@images/imageXHB/new-home/arrow-right.png";
import EyeOpen from "@images/imageXHB/new-home/eye-open.png";
import EyeClose from "@images/imageXHB/new-home/eye-close.png";
// import CustomerService from "@images/imageXHB/new-home/customer-service.png";
import SetUp from "@images/imageXHB/new-home/set-up.png";
import Notice from "@images/imageXHB/new-home/notice.png";
// eslint-disable-next-line camelcase
import xhb_foot from "@images/imageXHF/xhf_foot.png";
import { refresh } from "@/component/scroll/index2";
import titleLogo from "@images/imageXHB/xhb_title.png";
import ActivityModal from "@component/activityModal";
import BackModal from "./components/backModal/index";

import "react-quill/dist/quill.snow.css";
import "./WalletHomeNew.scss";

class WalletHomeNew extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isError: false,
			notificationArr: [],
			modal2: false,
			boardTitle: "",
			boardContent: "",
			objData: sessionStorage.getItem("walletHomeData")
				? JSON.parse(sessionStorage.getItem("walletHomeData"))
				: {
						nextProfit: "",
						nextProfitDay: "",
						rate: "0.00", // "0.00",//存款利率
						sumProfit: "0.00", //累积收益
						totalAmount: "0.00", //总金额
						totalCount: "", //总订单条数
						openStatus: "", //开户状态，0-已开户，1-未开户
						productFCode: "",
						productLabel: [], //产品标签
						productId: "",
						profitLabel: "",
						rateLabel: "",
						tradeNumber: "",
						electronicCardNo: "",
						balanceAmt: "0.00",
						saleStatus: 0,
						productDetail: {
							productName: "", //产品名称
							minMoney: "", //起投金额
							drawDate: "", //派息周期
							storeRule: [], //产品详情
							profitRule: [], //计息规则
							drawRule: [] //支取规则
						}
				  },
			loadStatus: "",
			isShowMoney: false,
			modal1: false,
			flag: true,
			activeVisible: false, //活动弹窗
			activeData: {}, //活动数据
			buttonArray: [],
			isShowTurnoutModal: false, // 是否显示转出挽留页
			turnoutModalData: { i: "", requrl: "" } //转出按钮弹出挽留页保留的参数
		};
		/** 是否完成数据加载
		 * 为了避免android底层框架无法并发ajax导致跳转其他界面后白屏或者界面数据异常的问题
		 * 加入该状态，跳转界面的操作都需要进行判断，必须要数据加载完成才进入*/
		this._isLoading = false;
		this._loadingTimer = null;
	}
	componentDidMount() {
		if (this.props.location.query) {
			this.setState({
				flag: false
			});
		}
		this.props._getAppPlatformsDatas({
			lnid: "1"
		});
		this.getInitData();
		this.queryPopupFrameRule();
	}
	componentWillUnmount() {
		if (this._loadingTimer) {
			clearTimeout(this._loadingTimer);
			this._loadingTimer = null;
		}
		if (this.alert2) {
			this.alert2.close();
		}
	}
	//获取活动弹窗
	queryPopupFrameRule = () => {
		let objs = {
			url: InterfaceG.queryPopupFrameRule,
			params: {
				pageCode: "xhbHomePage",
				productCode: "1"
			},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				if (res.data) {
					console.log(JSON.parse(res.data.buttonArray));
					this.setState({
						activeData: res.data,
						activeVisible: true,
						buttonArray: res.data.buttonArray
							? JSON.parse(res.data.buttonArray)
							: []
					});
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	//关闭活动弹窗
	onCloseAcitve = () => {
		this.setState({
			activeVisible: false
		});
	};
	getInitData() {
		let objs = {
			url: InterfaceG.holdingsInit,
			params: {
				channelCode: channelCode,
				productId: "1"
			},
			_alertShow: false
		};
		let _that = this;
		yhTools
			.request(objs)
			.then(res => {
				if (res.code === "0") {
					sessionStorage.setItem("walletHomeData", JSON.stringify(res.data));
					_that.setState(
						{
							objData: res.data
						},
						() => refresh()
					);
				} else {
					_that.setState({
						loadStatus: "1", // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败，'3'：系统正在升级）
						isError: true
					});
					Toast.info(res.message, 2);
				}
			})
			.then(() => {
				_that.getNotification();
			});
	}
	getNotification() {
		let objs = {
			url: "/fm/boardInfo",
			params: {
				boardType: "00",
				boardSubtype: "yhb"
			},
			_alertShow: false
		};
		// Toast.loading("加载中...", 100);
		let _that = this;
		yhTools
			.request(objs)
			.then(res => {
				if (res.code === "0") {
					_that.setState(
						{
							notificationArr: res.data
						},
						() => refresh()
					);
				} else {
					Toast.info(res.message, 2);
				}
			})
			.then(() => {});
	}
	loadingToast() {
		if (this._loadingTimer) {
			clearTimeout(this._loadingTimer);
		}
		this._loadingTimer = setTimeout(() => {
			Toast.info("数据加载中，请稍后再试", 2);
		}, 1000);
	}
	//查看协议
	openContract(v) {
		if (v === 1) {
			this.props.history.push({
				pathname: "/iframeAgreements",
				state: {
					src: agreements_url + "/privacyAgreement.html",
					title: "永辉金融隐私政策"
				}
			}); //《用户隐私协议》
		} else if (v === 2) {
			this.props.history.push(`/serviceAgreementAuthorization`); //《客户服务协议》
		}
	}
	formatMoney(str) {
		return Number(str.replace(/,/g, "")) > 0;
	}
	/**转入转出限制 */
	queryXhbBankLockStatus(i, requrl) {
		if (i === 1 && this.state.objData.saleStatus == "2") {
			//如果是转出并且已售罄，展示挽留页
			this.setState({
				isShowTurnoutModal: true,
				turnoutModalData: { i, requrl }
			});
			return;
		}
		this.confirmXhbBankLockStatus(i, requrl);
	}
	//确认转入转出
	confirmXhbBankLockStatus(i, requrl) {
		if (i === 1 && !this.formatMoney(this.state.objData.totalAmount)) {
			//转出
			return;
		}
		let objs = {
			url: requrl,
			params: {
				productId: this.state.objData.productId
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 15);
		yhTools
			.request(objs)
			.then(res => {
				Toast.hide();
				if (res.code === "0") {
					this.gotoNext(i);
				} else {
					Toast.info(res.message, 2);
				}
			})
			.then(() => {});
	}
	getText() {
		let obj = {
			0: "已停售",
			1: "确认转入",
			2: "今日已售罄，请明天早点来"
		};
		return obj[this.state.objData.saleStatus];
	}
	gotoNext(i) {
		let pageParams = {};
		if (i === 1) {
			//转出
			if (!this.formatMoney(this.state.objData.totalAmount)) {
				return;
			}
			// 判断已签约，并且有合并的订单才能进入一键转出界面
			if (
				this.state.objData.paySignStatus === "0" &&
				this.state.objData.mergeStatus == "0"
			) {
				//已开通
				pageParams = {
					url: `/transferXHBOutByPay/${this.state.objData.productId || ""}`
				};
			} else {
				//需要调用接口判断是否签约小辉宝支付
				pageParams = {
					url: `/depositDetail`
				};
			}
		} else if (i === 2) {
			//转入
			if (this.state.objData.saleStatus != "1") {
				Toast.info(this.getText(), 2);
				return;
			}
			pageParams = {
				url: `/transferXHBInto/${this.state.objData.productId || ""}`
			};
		} else if (i === 3) {
			pageParams = {
				url: `/walletInfo/${this.state.objData.productId || ""}`
			};
		} else if (i === 4) {
			this.appBtnMoney();
		} else if (i === 5) {
			pageParams = {
				url: `/cumulativeIncome`
			};
		} else if (i === 8) {
			pageParams = {
				url: `/bankDetailPage`
			};
		} else if (i === 10) {
			if (!this.formatMoney(this.state.objData.totalAmount)) {
				return;
			}
			pageParams = {
				url: `/depositDetail`
			};
		}
		this.props.history.push({
			pathname: pageParams.url,
			state: {
				statePrame: {
					backPath: "/walletHome"
				}
			}
		});
	}
	/**
	 * @description: 点击头部设置图标
	 */
	showModal = () => {
		// e.preventDefault(); // 修复 Android 上点击穿透
		this.setState({
			showDialog: "moreAccountDialog  wrapper-out",
			popContent: "",
			modal1: true
		});
	};
	onClose = () => () => {
		this.setState({
			modal1: false
		});
	};
	//开始赚钱点击接口
	appBtnMoney() {
		let objs = {
			url: InterfaceG.xhbVerifyIdentity,
			params: {
				channelCode,
				version: "1.0"
			}
		};
		let _that = this;
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				const { pageNo, userName, idNo, mobilePhone, signDate } = res.data;
				if (pageNo === "01") {
					// 开户
					_that.props.history.push({
						pathname: `/uploadIDCardImgPage`
					});
				} else if (pageNo === "02") {
					// 身份核实
					_that.props.history.push({
						pathname: `/identityVerification`,
						state: { userName, idNo, mobilePhone, signDate }
					});
				} else {
					this.getInitData();
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	// html反转义
	htmlDecode(text) {
		let temp = document.createElement("div");
		temp.innerHTML = text;
		let output = temp.innerText || temp.textContent;
		temp = null;
		return output;
	}
	// 获取存文本
	htmlDecodeToText(text) {
		let htmlText = this.htmlDecode(text);
		htmlText = htmlText
			.replace(/<\/?.+?>/g, "")
			.replace(/\ +/g, "")
			.replace(/[\r\n]/g, "")
			.replace(/&nbsp;/gi, "")
			.replace("&nbsp;", "")
			.replace("&nsp;", "")
			.replace(/\s*/g, "");
		return htmlText;
	}
	//去除br换行符
	formatText(str) {
		// eslint-disable-next-line no-useless-escape
		return str.replace(/[\<br\/\>|\<br\>]/g, "");
	}
	showAlert(b) {
		const { notificationArr = [] } = this.state;
		let str,
			title = "";
		str = notificationArr[0] ? notificationArr[0].boardContent : "";
		title = notificationArr[0] ? notificationArr[0].boardTitle : "";
		this.setState({
			modal2: b,
			boardContent: str, // this.htmlDecode(str)
			boardTitle: title
		});
	}
	//显示隐藏金额
	showMoney() {
		let isShowMoney = this.state.isShowMoney;
		this.setState({
			isShowMoney: !isShowMoney
		});
	}
	/**
	 * @description: 跳转交易明细
	 */
	gotoPopNext() {
		this.props.history.push({
			pathname: "/billRecord/1"
		});
	}
	/**
	 * @description: 点击头部客户图标
	 */
	onCustomer = () => {
		this.props.history.push({
			pathname: "/iframePage",
			state: {
				title: "在线客服",
				src:
					"https://jrsdk.sobot.com/chat/h5/v2/index.html?sysnum=fb2bdaba0d8c4fe2bb8ccfdf2a1f02be&channelid=3"
			}
		});
	};
	/**
	 * @description: 跳转银行贷款介绍页面
	 */
	onIntroduction = () => {
		let objData = this.state.objData;
		this.props.history.push({
			pathname: `/IntroductionBankLoans`,
			state: objData
		});
	};

	//转出挽留页事件
	onTurnoutModalClick = booleanValue => {
		this.setState({
			isShowTurnoutModal: false
		});
		const { turnoutModalData } = this.state;
		if (!booleanValue) {
			this.confirmXhbBankLockStatus(
				turnoutModalData.i,
				turnoutModalData.requrl
			);
		}
	};
	render() {
		const headerParams = {
			header: {
				title: "小辉宝",
				titleType: titleLogo,
				rightButt: (
					<div className="header-right">
						{/* <img src={CustomerService} onClick={this.onCustomer} /> */}
						{this.state.objData.totalCount > 0 && (
							<img src={SetUp} onClick={this.showModal} />
						)}
					</div>
				),
				goToApp: this.state.flag
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles,
			loadStatus: this.state.loadStatus // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败）
		};
		const tabs = [
			{ title: "产品详情" },
			{ title: "计息规则" },
			{ title: "支取规则" }
		];
		const {
			isShowMoney,
			notificationArr,
			modal2,
			boardTitle,
			boardContent,
			objData,
			isError,
			isShowTurnoutModal,
			activeVisible,
			activeData,
			buttonArray
		} = this.state;
		const {
			rate,
			sumProfit,
			totalAmount,
			openStatus,
			nextProfitDay,
			nextProfit,
			balanceAmt = 0.0,
			totalCount,
			productDetail = {},
			saleStatus
		} = objData;
		const {
			drawDate,
			minMoney,
			storeRule = [],
			profitRule = [],
			drawRule = []
		} = productDetail;
		return (
			<div style={{ height: "100%" }}>
				<MainLayout pageParams={headerParams} isScroll={true}>
					<Modal
						popup
						className="wallet-home-modal"
						visible={this.state.modal1}
						onClose={this.onClose("modal1")}
						animationType="slide-up"
					>
						<List className="popup-list">
							<List.Item>
								<div className="item" onClick={this.gotoPopNext.bind(this)}>
									交易明细
								</div>
							</List.Item>
							<List.Item>
								<div className="cancel-btn" onClick={this.onClose("modal1")}>
									取消
								</div>
							</List.Item>
						</List>
					</Modal>
					<Modal
						visible={modal2}
						transparent
						maskClosable={false}
						className="wallet-home-modal2"
					>
						<div className="payBack-play-box">
							<div className="payBack-play-heard">
								<h2>{boardTitle}</h2>
							</div>
							<div
								className="board-content-box ql-editor"
								style={{ textAlign: "left" }}
								dangerouslySetInnerHTML={{ __html: boardContent }}
							></div>
						</div>
						<div>
							<Button
								className="payBack-play-button"
								onClick={this.showAlert.bind(this, false)}
							>
								确定
							</Button>
						</div>
					</Modal>
					<BackModal
						isVisible={isShowTurnoutModal}
						onClick={this.onTurnoutModalClick}
					></BackModal>
					<div className="wallet-home-new">
						{notificationArr.length > 0 && (
							<NoticeBar
								icon={<img src={Notice} className="notice-ico" />}
								marqueeProps={{
									loop: true,
									style: { padding: "0 7.5px", color: "#F5A623" }
								}}
								onClick={this.showAlert.bind(this, true)}
							>
								{
									<span>
										{this.formatText(
											this.htmlDecodeToText(notificationArr[0].boardContent)
										)}
									</span>
								}
							</NoticeBar>
						)}
						{isError && (
							<div className="loading_error flexCenter">
								<div className="con">
									<div className="xhbbg_image"></div>
									<div className="text">系统正在升级…</div>
									<div className="text-two">给您带来的不便，敬请谅解~</div>
								</div>
							</div>
						)}

						{!isError && totalCount > 0 ? (
							<div className="header-detail">
								<p className="title">总金额（元）</p>
								<span className="money" onClick={this.gotoNext.bind(this, 10)}>
									{totalAmount}
								</span>
								<div className="estimate">
									<img src={ArrowLeft} />
									{nextProfitDay}日后预计到账<span>{nextProfit}元</span>买菜钱
									<img src={ArrowRight} />
								</div>
								<ul>
									<li onClick={this.gotoNext.bind(this, 5)}>
										<p>累计收益（元）</p>
										<span>{sumProfit}</span>
									</li>
									<li>
										<p>存款利息（%）</p>
										<span>{rate}%</span>
									</li>
								</ul>
							</div>
						) : (
							!isError && (
								<div className="header-introduce">
									<div className="introduce-title">
										<p>
											<img src={HedaerIco} />
											小辉宝
										</p>
										<span onClick={this.onIntroduction}>银行存款是什么?</span>
									</div>
									<div className="introduce-content">
										<div className="content-left">
											<p>
												{rate}
												<i>%</i>
											</p>
											<span>储蓄存款利率</span>
										</div>
										<div className="content-right">
											<p>
												<i>派息周期</i>
												<span>{drawDate}</span>
											</p>
											<p>
												<i>起投金额</i>
												<span>{minMoney || 0}元</span>
											</p>
										</div>
									</div>
									<div className="introduce-footer">
										<ul>
											<li>
												<img src={FooterIco} />
												银行精选
											</li>
											<li>储蓄存款</li>
											<li>收益稳定</li>
										</ul>
									</div>
								</div>
							)
						)}
						{!isError && openStatus == "0" && (
							<div className="balance-box">
								<div className="balance-left">
									<span>电子账号余额（元）</span>
									<i className={isShowMoney ? "" : "line-h"}>
										{isShowMoney ? balanceAmt : "****"}
									</i>
									<span
										key={Math.random()}
										className="eye"
										onClick={this.showMoney.bind(this)}
									>
										<img src={isShowMoney ? EyeOpen : EyeClose} />
									</span>
								</div>
								<div
									className="balance-right"
									onClick={this.gotoNext.bind(this, 8)}
								></div>
							</div>
						)}
						{!isError && (
							<div className="detail-box">
								<div className="list-three">
									<ul>
										<li>
											<img src={ListOne} />
											<p>当日起息</p>
											<span>节假日均适用</span>
										</li>
										<li>
											<img src={ListTow} />
											<p>灵活支用</p>
											<span>下周一可随时支取</span>
										</li>
										<li>
											<img src={ListThree} />
											<p>本息保障</p>
											<span>50万以内100%赔付</span>
										</li>
									</ul>
								</div>
								<div className="detail-tab">
									<Tabs tabs={tabs} initialPage={0}>
										<div>
											{storeRule && storeRule.length > 0
												? storeRule.map(item => {
														return (
															<dl key={item.key}>
																<dt>{item.key}：</dt>
																<dd>{item.value}</dd>
															</dl>
														);
												  })
												: ""}
										</div>
										<div>
											{profitRule && profitRule.length > 0
												? profitRule.map(item => {
														return (
															<dl key={item.key}>
																<dt>{item.key}：</dt>
																<dd>{item.value}</dd>
															</dl>
														);
												  })
												: ""}
										</div>
										<div>
											{drawRule && drawRule.length > 0
												? drawRule.map(item => {
														return (
															<dl key={item.key}>
																<dt>{item.key}：</dt>
																<dd>{item.value}</dd>
															</dl>
														);
												  })
												: ""}
										</div>
									</Tabs>
								</div>
								{openStatus == "0" && totalCount > 0 && (
									<div className="bank-infor" onClick={this.onIntroduction}>
										银行存款是什么？ >
									</div>
								)}
								{openStatus == "1" && (
									<div className="detail-course">
										<div className="title">小辉宝如何开通？</div>
										<div className="img-bg">
											<img src={Course} />
										</div>
									</div>
								)}
								{totalCount <= 0 && (
									<div className="detail-risk-statement">
										<img src={RiskStatement} />
									</div>
								)}
							</div>
						)}
						<div className="xhb-index-footer">
							<img src={xhb_foot} alt="" />
						</div>
					</div>
				</MainLayout>
				<ActivityModal
					activeVisible={activeVisible}
					onCloseAcitve={this.onCloseAcitve}
					activeData={activeData}
					buttonArray={buttonArray}
					history={this.props.history}
				/>
				{!isError && (
					<div className="btn-box">
						{openStatus == "1" && (
							<Fragment>
								<div className="contract_content">
									<p className="huise">点击按钮，表示您已阅读并同意</p>
									<p className="xieyi-p">
										<a
											className="xieyi"
											onClick={this.openContract.bind(this, 1)}
										>
											《永辉金融隐私政策》
										</a>
										<a
											className="xieyi"
											onClick={this.openContract.bind(this, 2)}
										>
											《永辉金融用户协议》
										</a>
									</p>
								</div>
								{saleStatus == "2" ? (
									<div className="btn-common btn-disable">产品已售罄</div>
								) : (
									<div
										className="btn-common"
										onClick={this.gotoNext.bind(this, 4)}
									>
										立即存入
									</div>
								)}
							</Fragment>
						)}
						{/* 未购买 */}
						{openStatus == "0" && totalCount <= 0 && (
							<>
								{saleStatus == "2" ? (
									<div className="btn-common btn-disable one-btn">
										产品已售罄
									</div>
								) : (
									<div
										className="btn-common one-btn"
										onClick={this.queryXhbBankLockStatus.bind(
											this,
											2,
											InterfaceG.queryXhbBuyBtnLockStatus
										)}
									>
										立即存入
									</div>
								)}
							</>
						)}
						{/* 已购买 */}
						{openStatus == "0" && totalCount > 0 && (
							<div className="one-btn">
								<div
									onClick={this.queryXhbBankLockStatus.bind(
										this,
										1,
										InterfaceG.queryXhbRedeemBtnLockStatus
									)}
								>
									转出
								</div>
								{saleStatus == "2" ? (
									<div className="out btn-disable">产品已售罄</div>
								) : (
									<div
										className="out"
										onClick={this.queryXhbBankLockStatus.bind(
											this,
											2,
											InterfaceG.queryXhbBuyBtnLockStatus
										)}
									>
										转入
									</div>
								)}
							</div>
						)}
					</div>
				)}
			</div>
		);
	}
}
function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps(dispatch) {
	return {
		_getAppPlatformsDatas: abj => {
			//获取native的数据
			dispatch(getAppPlatformsDatas(abj));
		}
	};
}

const WalletHomePage = connect(
	mapStateToProps,
	mapDispatchToProps
)(WalletHomeNew);

export default WalletHomePage;
